import Clipboard from "clipboard";
// import { Toast } from "vant";
// import Clipboard from "clipboard";
function clipboardSuccess() {
	// Toast.clear(true);
}

function clipboardError() {
	// Toast.clear(true);
	// Toast({
	// 	message: "复制失败",
	// 	position: "top"
	// });
}
export function copy(text, event, cb) {
	const clipboard = new Clipboard(event.target, {
		text: () => text
	});
	clipboard.on("success", () => {
		clipboardSuccess();
		clipboard.destroy();
		cb && cb(true);
	});
	clipboard.on("error", () => {
		clipboardError();
		clipboard.destroy();
		cb && cb(false);
	});
	clipboard.onClick(event);
}

export default {
	bind(el, binding) {
		if (binding.arg === "success") {
			el._v_clipboard_success = binding.value;
		} else if (binding.arg === "error") {
			el._v_clipboard_error = binding.value;
		} else {
			const clipboard = new Clipboard(el, {
				text() {
					return binding.value;
				},
				action() {
					return binding.arg === "cut" ? "cut" : "copy";
				}
			});
			clipboard.on("success", (e) => {
				const callback = el._v_clipboard_success;
				if (!callback) {
					clipboardSuccess();
					return;
				}
				callback(e);
			});
			clipboard.on("error", (e) => {
				const callback = el._v_clipboard_error;
				if (!callback) {
					clipboardError();
					return;
				}
				callback(e);
			});
			el._v_clipboard = clipboard;
		}
	},
	update(el, binding) {
		if (binding.arg === "success") {
			el._v_clipboard_success = binding.value;
		} else if (binding.arg === "error") {
			el._v_clipboard_error = binding.value;
		} else {
			el._v_clipboard.text = function () {
				return binding.value;
			};
			el._v_clipboard.action = function () {
				return binding.arg === "cut" ? "cut" : "copy";
			};
		}
	},
	unbind(el, binding) {
		if (binding.arg === "success") {
			delete el._v_clipboard_success;
		} else if (binding.arg === "error") {
			delete el._v_clipboard_error;
		} else {
			el._v_clipboard.destroy();
			delete el._v_clipboard;
		}
	}
};
